package com.youlu.campus.service.ad.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.UserActivityPointDetail;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.ad.UserTaskAdsRecord;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.ad.UserTaskAdsRecordService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class UserTaskAdsRecordServiceImpl implements UserTaskAdsRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityTaskService activityTaskService;
    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;

    @Override
    public UserTaskAdsRecord create(UserTaskAdsRecord req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        return req;
    }

    @Override
    public boolean update(UserTaskAdsRecord req) {
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (StringUtils.isNotBlank(req.getStatus())) {
            update.set("status", req.getStatus());
        }
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, UserTaskAdsRecord.class);
        boolean re = updateResult.getModifiedCount() > 0 ? true : false;
        log.info(":>>> 更新广告记录:{} 结果:{}", req.getId(), re);
        return re;
    }

    @Override
    public UserTaskAdsRecord findById(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, UserTaskAdsRecord.class);
    }

    @Override
    public UserTaskAdsRecord find(String userId, String taskId, String platform, String appId) {
        if (StringUtils.isBlank(userId) || Objects.isNull(taskId)) {
            log.error(":>>> 查询用户广告记录参数错误");
            throw new BusinessException("查询用户广告记录参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("taskId")
                .is(taskId).and("platform").is(platform).and("appId").is(appId));
        return mongoTemplate.findOne(query, UserTaskAdsRecord.class);
    }

    @Override
    public UserTaskAdsRecord startViewAd(String userId, String adId, String platfrom, String appId, String taskId) {
        if (StringUtils.isBlank(userId) || Objects.isNull(taskId)) {
            log.error(":>>> 查询用户广告记录参数错误");
            throw new BusinessException("查询用户广告记录参数错误");
        }
        UserTaskAdsRecord u = this.find(userId, taskId, platfrom, appId);
        if (Objects.nonNull(u)) {
            return u;
        }
        u = new UserTaskAdsRecord();
        u.setUserId(userId);
        u.setPlatfrom(platfrom);
        u.setAppId(appId);
        u.setStatus("doing");
        u.setTaskId(taskId);
        u.setCreatedTime(new Date());
        u.setAdsInfoId(adId);
        return this.create(u);
    }

    @Override
    public boolean endViewAd(UserPO userPO, String id) {
        UserTaskAdsRecord userAdsRecord = this.findById(id);
        if (Objects.isNull(userAdsRecord)) {
            log.error(":>>> 用户广告记录不存在:{}", id);
            throw new BusinessException("用户广告记录不存在");
        }
        log.info(":>>> 广告记录的状态:{},{}", id, userAdsRecord.getStatus());
        if ("done".equals(userAdsRecord.getStatus())) {
            return true;
        }
        Date date = new Date();
        userAdsRecord.setStatus("done");
        boolean re = this.update(userAdsRecord);
        if (re) {
            ActivityTaskInfo taskInfo = activityTaskService.findOne(userAdsRecord.getTaskId());
            Integer point = taskInfo.getPoints().intValue();
            UserActivityPointDetail detail = new UserActivityPointDetail();
            detail.setUserId(userAdsRecord.getUserId());
            detail.setAction("add");
            detail.setActivityId(taskInfo.getActivityId());
            detail.setBizDesc("观看视频");
            detail.setBizType("add");
            detail.setOptDate(date);
            detail.setPoints(point);
            detail.setComments("观看视频" + point + "积分");
            userActivityPointRankingService.updatePoint(userPO, "", point);
            return true;
        }
        return false;
    }
}
